/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="app-container" ref="channel-container">
    <el-dialog
      width="770px"
      top="6vh"
      :visible.sync="diagramVisible"
      :title="$t('edge.channel.diagramtitle')"
      :close-on-click-modal="false"
      custom-class="WiringDiagram"
      @close="closeWiringDiagram"
      append-to-body>
      <WiringDiagram />
    </el-dialog>
    <el-button style="margin-bottom:10px" type="primary" @click="onAdd">{{$t('edge.common.add')}}</el-button>
    <el-button style="margin-bottom:10px" type="primary" @click="deleteAllData">{{$t('edge.common.deleteall')}}</el-button>
    <el-button style="margin-bottom:10px" type="primary" @click="openWiringDiagram">{{$t('edge.channel.wiringdiagram')}}</el-button>
    <el-table class="tb-edit" ref="singleTable" :data="channelList" v-loading.body="listLoading" element-loading-text="Loading" fit highlight-current-row :max-height="tableHeight" v-clickoutside="cancelTable" id="footerBtn">
      <el-table-column align="center" label='ID' min-width="40">
        <template slot-scope="scope">
          <span>{{scope.row.id}}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" :label="$t('edge.channel.desc')" prop="desc" min-width="100">
        <template slot-scope="scope">
          <el-select v-model="scope.row.desc" :placeholder="$t('edge.common.select')" size="small" clearable>
            <el-option
              v-for="item in signLocationList"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </template>
      </el-table-column> -->
      <el-table-column align="center" :label="$t('edge.channel.controlType')" prop="typeAndSouce" min-width="200">
        <template slot-scope="scope">
          <el-cascader
            size="medium"
            expand-trigger="hover"
            :options="typeOptions"
            v-model="scope.row.typeAndSouce"
            class="config"
            clearable
            @change="handleChange(scope.row.typeAndSouce, scope.$index, scope.row)">
          </el-cascader>
          <span v-text="getTypeAndSouce(scope.row)"></span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('edge.channel.type')" prop="direction" min-width="100">
        <template slot-scope="scope">
          <el-select @clear="clearType" v-model="scope.row.type" @change="typeChange(scope.row,scope.$index)" :placeholder="$t('edge.common.select')" size="small" clearable>
            <el-option
              v-for="item in channeltypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <span v-text="getControlTypestr(scope.row)"></span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('edge.channel.orientation')" prop="direction" min-width="100">
        <!-- <template slot-scope="scope">
          <el-select v-model="scope.row.realdir" @focus="turnChange(scope.row.type,scope.$index)" multiple :placeholder="$t('edge.common.select')" size="small" @clear="clearRealdir" clearable>
            <el-option
              v-for="item in realdirOptions[scope.$index]"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <span v-text="getRealdir(scope.row, scope.$index)"></span>
        </template> -->
         <template slot-scope="scope">
          <el-select v-model="scope.row.realdir" @focus="turnChange(scope.row.type,scope.$index)" multiple :placeholder="$t('edge.common.select')" size="small" @clear="clearRealdir" clearable>
            <el-option
              v-for="item in realdirOptions.get(scope.row.id)"
              :key="item.value"
              :label="item.label"
              :value="item.value">
              <div class="single-model" >
                <xdrdirselector Width="60px" Height="60px" :showlist="item.item"></xdrdirselector>
                <span style="float: right; margin-left: 10px; color: #8492a6; font-size: 13px">{{ item.label }}</span>
              </div>
            </el-option>
          </el-select>
          <span>
            <xdrdirselector :Data="Data" :Datas="Datas" v-if="scope.row.realdir && scope.row.realdir.length > 0" Width="60px" Height="60px" :showlist="getDirectionList(scope.row)"></xdrdirselector>
          </span>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" :label="$t('edge.phase.lane')">
        <template slot-scope="scope">
          <el-input size="small" v-model="scope.row.lane" oninput="this.value=this.value.replace(/[^\d\,]/g,'')"></el-input>
        </template>
      </el-table-column> -->

      <el-table-column align="center" :label="$t('edge.channel.voltthresh')">
        <template slot-scope="scope">
          <el-input-number size="small" controls-position="right" :min="5" :max="200" :step="1" v-model.number="scope.row.voltthresh" style="width: 100px;"></el-input-number>
          <span>{{scope.row.voltthresh}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('edge.channel.pacthresh')">
        <template slot-scope="scope">
          <el-input-number size="small" controls-position="right" :min="1" :max="2000" :step="1" v-model.number="scope.row.pacthresh" style="width: 100px;"></el-input-number>
           <span>{{scope.row.pacthresh}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('edge.channel.peakhthresh')">
        <template slot-scope="scope">
          <el-input-number size="small" controls-position="right" :min="100" :max="1000" :step="1" v-model.number="scope.row.peakhthresh" style="width: 100px;"></el-input-number>
          <span>{{scope.row.peakhthresh}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('edge.channel.peaklthresh')">
        <template slot-scope="scope">
          <el-input-number size="small" controls-position="right" :min="100" :max="1000" :step="1" v-model.number="scope.row.peaklthresh" style="width: 100px;"></el-input-number>
          <span>{{scope.row.peaklthresh}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('edge.channel.direction')" prop="direction" min-width="100">
        <template slot-scope="scope">
          <el-select v-model="scope.row.direction" :placeholder="$t('edge.common.select')" size="small" clearable @clear="clearValue">
            <el-option
              v-for="item in signLocationList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <span v-text="getDirection(scope.row)"></span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('edge.channel.turn')" prop="direction" min-width="100">
        <template slot-scope="scope">
          <el-select v-model="scope.row.turn" @focus="turnChange(scope.row.type,scope.$index)" multiple :placeholder="$t('edge.common.select')" size="small" clearable>
            <el-option
              v-for="item in turnOptions.get(scope.row.id)"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <span v-text="getTurn(scope.row, scope.$index)"></span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('edge.channel.operation')">
        <template slot-scope="scope">
          <el-button type="text" @click="handleClone(scope.$index,scope.row)">{{$t('edge.common.clone')}}</el-button>
          <el-button type="text"  @click="handleDelete(scope.$index,scope.row)">{{$t('edge.common.delete')}}</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { getPhaseDesc } from '@/utils/phasedesc.js'
import { getPedPhaseDesc } from '@/utils/pedphasedesc.js'
import xdrdirselector from '@/components/XRDDirSelector'
import { getTheme } from '@/utils/auth'
import PhaseDataModel from 'openatc-components/package/kisscomps/components/IntersectionMap/crossDirection/utils'
import { getControSource, getOverLap, refreshChannelLockDescData, refreshControlPanelDescData, getTypeOptions, getEtypeOptions } from '@/utils/channeldesc.js'
import WiringDiagram from '@/components/WiringDiagram/index'
const TypeOptions = [{
  value: 1,
  // label: 'other'
  label: 'edge.channel.other'
}, {
  value: 2,
  // label: 'phaseVehicle'
  label: 'edge.channel.phaseVehicle'
}, {
  value: 3,
  // label: 'phasePedestrian'
  label: 'edge.channel.phasePedestrian'
}, {
  value: 4,
  // label: 'overlap'
  label: 'edge.channel.overlap'
}]
const clickoutside = {
  // 初始化指令
  bind (el, binding, vnode) {
    function documentHandler (e) {
      // 这里判断点击的元素是否是本身，是本身，则返回
      if (el.contains(e.target)) {
        return false
      }
      // 判断指令中是否绑定了函数
      if (binding.expression) {
        // 如果绑定了函数 则调用那个函数，此处binding.value就是handleClose方法
        binding.value(e)
      }
    }
    // 给当前元素绑定个私有变量，方便在unbind中可以解除事件监听
    el.__vueClickOutside__ = documentHandler
    document.addEventListener('click', documentHandler)
  },
  update () {},
  unbind (el, binding) {
    // 解除事件监听
    document.removeEventListener('click', el.__vueClickOutside__)
    delete el.__vueClickOutside__
  }
}
export default {
  name: 'channel',
  components: { xdrdirselector, WiringDiagram },
  data () {
    return {
      tableHeight: 760,
      listLoading: false,
      id: 1,
      // isChange: false,
      typeOptions: [],
      sidewalkPhaseData: [],
      // linkPhaseOption: [],
      Data: {
        left: '60px',
        top: '10px'
      },
      Datas: {
        left: '60px',
        top: '10px'
      },
      channeltypeOptions: [
        {
          value: 0,
          label: this.$t('edge.channel.type0')
        },
        {
          value: 1,
          label: this.$t('edge.channel.type1')
        },
        {
          value: 2,
          label: this.$t('edge.channel.type2')
        },
        {
          value: 3,
          label: this.$t('edge.channel.type3')
        },
        {
          value: 4,
          label: this.$t('edge.channel.type4')
        }
      ],
      turnOptions: new Map(),
      realdirOptions: new Map(),
      carList: [
        {
          value: 0,
          label: this.$t('edge.channel.turn0')
        },
        {
          value: 1,
          label: this.$t('edge.channel.turn1')
        },
        {
          value: 2,
          label: this.$t('edge.channel.turn2')
        },
        {
          value: 3,
          label: this.$t('edge.channel.turn3')
        },
        {
          value: 4,
          label: this.$t('edge.channel.turn8')
        }
      ],
      peopleList: [
        {
          value: 4,
          label: this.$t('edge.channel.turn4')
        },
        {
          value: 5,
          label: this.$t('edge.channel.turn5')
        },
        {
          value: 6,
          label: this.$t('edge.channel.turn6')
        },
        {
          value: 7,
          label: this.$t('edge.channel.turn7')
        }
      ],
      turnList: [
        {
          label: this.$t('edge.channel.type0'),
          children: [
            {
              value: 0,
              label: this.$t('edge.channel.turn0')
            },
            {
              value: 1,
              label: this.$t('edge.channel.turn1')
            },
            {
              value: 2,
              label: this.$t('edge.channel.turn2')
            },
            {
              value: 3,
              label: this.$t('edge.channel.turn3')
            },
            {
              value: 4,
              label: this.$t('edge.channel.turn8')
            }
          ]
        },
        {
          label: this.$t('edge.channel.type1'),
          children: [
            {
              value: 0,
              label: this.$t('edge.channel.turn0')
            },
            {
              value: 1,
              label: this.$t('edge.channel.turn1')
            },
            {
              value: 2,
              label: this.$t('edge.channel.turn2')
            },
            {
              value: 3,
              label: this.$t('edge.channel.turn3')
            },
            {
              value: 4,
              label: this.$t('edge.channel.turn8')
            }
          ]
        },
        {
          label: this.$t('edge.channel.type2'),
          children: [
            {
              value: 4,
              label: this.$t('edge.channel.turn4')
            },
            {
              value: 5,
              label: this.$t('edge.channel.turn5')
            },
            {
              value: 6,
              label: this.$t('edge.channel.turn6')
            },
            {
              value: 7,
              label: this.$t('edge.channel.turn7')
            }
          ]
        },
        {
          label: this.$t('edge.channel.type3'),
          children: [
            {
              value: 0,
              label: this.$t('edge.channel.turn0')
            },
            {
              value: 1,
              label: this.$t('edge.channel.turn1')
            },
            {
              value: 2,
              label: this.$t('edge.channel.turn2')
            },
            {
              value: 3,
              label: this.$t('edge.channel.turn3')
            },
            {
              value: 4,
              label: this.$t('edge.channel.turn8')
            }
          ]
        },
        {
          label: this.$t('edge.channel.type4'),
          children: [
            {
              value: 0,
              label: this.$t('edge.channel.turn0')
            },
            {
              value: 1,
              label: this.$t('edge.channel.turn1')
            },
            {
              value: 2,
              label: this.$t('edge.channel.turn2')
            },
            {
              value: 3,
              label: this.$t('edge.channel.turn3')
            },
            {
              value: 4,
              label: this.$t('edge.channel.turn8')
            }
          ]
        }
      ],
      signLocationList: [
        {
          value: 0,
          label: this.$t('edge.channel.direction0')
        },
        {
          value: 1,
          label: this.$t('edge.channel.direction1')
        },
        {
          value: 2,
          label: this.$t('edge.channel.direction2')
        },
        {
          value: 3,
          label: this.$t('edge.channel.direction3')
        },
        {
          value: 4,
          label: this.$t('edge.channel.direction4')
        },
        {
          value: 5,
          label: this.$t('edge.channel.direction5')
        },
        {
          value: 6,
          label: this.$t('edge.channel.direction6')
        },
        {
          value: 7,
          label: this.$t('edge.channel.direction7')
        }
      ],
      desclist: [], // 当前控制类型描述map
      diagramVisible: false
    }
  },
  directives: { clickoutside },
  filters: {
    statusFilter (status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  computed: {
    TypeOption () {
      let arrays = []
      TypeOptions.forEach(v => {
        let obj = Object.assign({}, v)
        obj.label = this.$t(obj.label)
        arrays.push(obj)
      })
      return arrays
    },
    ...mapState({
      channelList: state => state.globalParam.tscParam.channelList,
      channelDescMap: state => state.globalParam.channelDescMap
    })
  },
  created () {
    this.PhaseDataModel = new PhaseDataModel()
    this.globalParamModel = this.$store.getters.globalParamModel
    // this.linkPhaseOption = phaseList
    this.init()
  },
  mounted: function () {
    var _this = this
    _this.$nextTick(function () {
      _this.tableHeight = _this.$refs['channel-container'].offsetHeight - 90
      window.onresize = function () {
        _this.tableHeight = _this.$refs['channel-container'].offsetHeight - 90
      }
    })
  },
  watch: {
    channelList: function () {
      this.init()
      this.createCurrentDescMap()
    },
    channelDescMap: function () {
      refreshChannelLockDescData()
      refreshControlPanelDescData()
    }
  },
  methods: {
    getControlTypestr (val) {
      if (val.type === '') {
        return ''
      }
      if (val.type !== undefined) {
        return this.channeltypeOptions.filter(ele => ele.value === val.type)[0].label
      }
      return ''
    },
    getTurn (val, index) {
      if (val.turn !== undefined && val.turn.length > 0 && this.turnOptions.get(val.id)) {
        let desc = []
        for (let i = 0; i < val.turn.length; i++) {
          let label = this.turnOptions.get(val.id).filter(ele => ele.value === val.turn[i])[0].label
          desc.push(label)
        }
        return desc.join('')
      }
    },
    getRealdir (val, index) {
      if (val.realdir !== undefined && val.realdir.length > 0 && this.realdirOptions.get(val.id)) {
        let desc = []
        for (let i = 0; i < val.realdir.length; i++) {
          let label = this.realdirOptions.get(val.id).filter(ele => ele.value === val.realdir[i])[0].label
          desc.push(label)
        }
        return desc.join('')
      }
    },
    getDirectionList (val) {
      if (val.type === 0 || val.type === 1 || val.type === 3) {
        let dirArr = []
        let color = getTheme() === 'light' ? '#1E1E1E' : '#F1F3F4'
        for (let rec of val.realdir) {
          let recd = {
            id: rec,
            color: color
          }
          dirArr.push(recd)
        }
        return dirArr
      } else if (val.type === 2) {
        let dirArr = []
        let color = getTheme() === 'light' ? '#1E1E1E' : '#F1F3F4'
        let recd = {
          peddirection: this.getPeds(val.realdir),
          color: color
        }
        dirArr.push(recd)
        return dirArr
      } else {
        let dirArr = []
        let color = getTheme() === 'light' ? '#1E1E1E' : '#F1F3F4'
        let recd = {
          id: '',
          peddirection: [],
          color: color
        }
        dirArr.push(recd)
        return dirArr
      }
    },
    getPeds (data) {
      if (data.length === 0) return
      let ped = []
      let peddirections = []
      let color = getTheme() === 'light' ? '#1E1E1E' : '#F1F3F4'
      for (let walk of data) {
        let objs = {}
        objs.name = new PhaseDataModel().getSidePos(walk).name
        objs.id = walk
        objs.color = color
        peddirections.push(objs)
        peddirections = Array.from(new Set(peddirections))
      }
      ped.push(...peddirections)
      return ped
    },
    getDirection (val) {
      if (val.direction !== undefined) {
        return this.signLocationList.filter(ele => ele.value === val.direction)[0].label
      }
      return ''
    },
    cancelTable (e) {
      this.$refs.singleTable.setCurrentRow()
    },
    getTypeAndSouce (ele) {
      if (!ele.typeAndSouce || ele.typeAndSouce.length === 0) return
      let source
      let dire
      let desc = []
      if (ele.typeAndSouce[0] !== undefined) {
        source = this.typeOptions.filter(type => type.value === ele.typeAndSouce[0])[0].label
        desc[0] = source
      }
      if (ele.typeAndSouce[1] !== undefined) {
        this.typeOptions.forEach(type => {
          if (type.value === ele.typeAndSouce[0] && type.children && type.children.length) {
            dire = type.children.filter(child => child.value === ele.typeAndSouce[1])[0].label
          }
        })
        desc[1] = dire
      }
      return desc[0] + (desc[1] ? '/' : '') + (desc[1] ? desc[1] : '')
    },
    clearValue () {
      let channel = this.globalParamModel.getParamsByType('channelList')
      for (let i = 0; i < channel.length; i++) {
        if (channel[i].direction === '') {
          delete channel[i].direction
        }
      }
    },
    clearRealdir () {
      let channel = this.globalParamModel.getParamsByType('channelList')
      for (let i = 0; i < channel.length; i++) {
        if (channel[i].realdir && channel[i].realdir.length === 0) {
          channel[i].realdir = []
        }
      }
    },
    clearType () {
      let channel = this.globalParamModel.getParamsByType('channelList')
      for (let i = 0; i < channel.length; i++) {
        if (channel[i].type === '') {
          delete channel[i].type
        }
      }
    },
    turnChange (val, index) {
      if (val || val === 0) {
        this.turnOptions.set(val.id, [])
        this.turnOptions.set(val.id, this.turnList[val].children)
      }
    },
    typeChange (val, index) {
      let color = getTheme() === 'light' ? '#1E1E1E' : '#F1F3F4'
      this.turnOptions.set(val.id, [])
      // let phaseList = this.globalParamModel.getParamsByType('phaseList')
      let channel = this.globalParamModel.getParamsByType('channelList')
      let overlap = this.globalParamModel.getParamsByType('overlaplList')
      channel[index].turn = []
      for (let i = 0; i < this.channeltypeOptions.length; i++) {
        if (this.channeltypeOptions[i].value === val.type) {
          this.turnOptions.set(val.id, this.turnList[this.channeltypeOptions[i].value].children)
        }
      }
      if (val.controltype === 6 && val.type === 0) {
        let status = [
          {
            item: [{
              id: 1,
              color: color
            }],
            label: getPhaseDesc([1], this.$i18n.locale),
            value: 1
          },
          {
            item: [{
              id: 2,
              color: color
            }],
            label: getPhaseDesc([2], this.$i18n.locale),
            value: 2
          },
          {
            item: [{
              id: 3,
              color: color
            }],
            label: getPhaseDesc([3], this.$i18n.locale),
            value: 3
          },
          {
            item: [{
              id: 4,
              color: color
            }],
            label: getPhaseDesc([4], this.$i18n.locale),
            value: 4
          },
          {
            item: [{
              id: 5,
              color: color
            }],
            label: getPhaseDesc([5], this.$i18n.locale),
            value: 5
          },
          {
            item: [{
              id: 6,
              color: color
            }],
            label: getPhaseDesc([6], this.$i18n.locale),
            value: 6
          },
          {
            item: [{
              id: 7,
              color: color
            }],
            label: getPhaseDesc([7], this.$i18n.locale),
            value: 7
          },
          {
            item: [{
              id: 8,
              color: color
            }],
            label: getPhaseDesc([8], this.$i18n.locale),
            value: 8
          },
          {
            item: [{
              id: 9,
              color: color
            }],
            label: getPhaseDesc([9], this.$i18n.locale),
            value: 9
          },
          {
            item: [{
              id: 10,
              color: color
            }],
            label: getPhaseDesc([10], this.$i18n.locale),
            value: 10
          },
          {
            item: [{
              id: 11,
              color: color
            }],
            label: getPhaseDesc([11], this.$i18n.locale),
            value: 11
          },
          {
            item: [{
              id: 12,
              color: color
            }],
            label: getPhaseDesc([12], this.$i18n.locale),
            value: 12
          },
          {
            item: [{
              id: 13,
              color: color
            }],
            label: getPhaseDesc([13], this.$i18n.locale),
            value: 13
          },
          {
            item: [{
              id: 14,
              color: color
            }],
            label: getPhaseDesc([14], this.$i18n.locale),
            value: 14
          },
          {
            item: [{
              id: 15,
              color: color
            }],
            label: getPhaseDesc([15], this.$i18n.locale),
            value: 15
          },
          {
            item: [{
              id: 16,
              color: color
            }],
            label: getPhaseDesc([16], this.$i18n.locale),
            value: 16
          }
        ]
        channel[index].realtype = 'direction'
        this.realdirOptions.set(val.id, status)
      } else {
        if (val.controltype !== 6 && (val.type === 0 || val.type === 1 || val.type === 3)) {
          channel[index].realdir = []
          channel[index].realtype = 'direction'
          if (val.controltype === 4 || val.controltype === 5) {
            if (!overlap.filter(phase => phase.id === val.controlsource)[0].direction) {
              this.realdirOptions.set(val.id, [])
              return
            }
            this.realdirOptions.set(val.id, overlap.filter(phase => phase.id === val.controlsource)[0].direction.map(item => ({value: item, item: [{ id: item, peddirection: [], color: color }], label: getPhaseDesc([item], this.$i18n.locale)})))
          } else {
            this.realdirOptions.set(val.id, this.globalParamModel.getParamsByType('phaseList').filter(phase => phase.id === val.controlsource)[0].direction.map(item => ({value: item, item: [{ id: item, peddirection: [], color: color }], label: getPhaseDesc([item], this.$i18n.locale)})))
          }
          // this.realdirOptions[index] = phaseList.filter(phase => phase.id === channel[index].controlsource)[0].direction.map(item => ({value: item, label: getPhaseDesc([item])}))
        } else if (val.controltype !== 6 && val.type === 2) {
          channel[index].realdir = []
          channel[index].realtype = 'peddirection'
          if (val.controltype === 4 || val.controltype === 5) {
            if (!overlap.filter(phase => phase.id === val.controlsource)[0].peddirection) {
              this.realdirOptions.set(val.id, [])
              return
            }
            this.realdirOptions.set(val.id, overlap.filter(phase => phase.id === val.controlsource)[0].peddirection.map(item => ({value: item, item: [{ id: 0, peddirection: this.getPed(item), color: color }], label: getPedPhaseDesc([item], this.$i18n.locale)})))
          } else {
            this.realdirOptions.set(val.id, this.globalParamModel.getParamsByType('phaseList').filter(phase => phase.id === channel[index].controlsource)[0].peddirection.map(item => ({value: item, item: [{ id: 0, peddirection: this.getPed(item), color: color }], label: getPedPhaseDesc([item], this.$i18n.locale)})))
            // this.realdirOptions[index] = this.globalParamModel.getParamsByType('phaseList').filter(phase => phase.id === val.controlsource)[0].direction.map(item => ({value: item, label: getPhaseDesc([item])}))
          }
          // this.realdirOptions[index] = phaseList.filter(phase => phase.id === channel[index].controlsource)[0].peddirection.map(item => ({value: item, label: getPedPhaseDesc([item])}))
        } else {
          channel[index].realtype = ''
          channel[index].realdir = []
          this.realdirOptions.set(val.id, [])
        }
      }
    },
    init () {
      this.initData()
      this.increaseId()
    },
    getPedPhasePos (phaseList) {
      // 行人相位信息
      this.sidewalkPhaseData = []
      phaseList.forEach((ele, i) => {
        if (ele.peddirection) {
          ele.peddirection.forEach((dir, index) => {
          // 行人相位
            if (this.PhaseDataModel.getSidePos(dir)) {
              this.sidewalkPhaseData.push({
                // key: this.CrossDiagramMgr.getUniqueKey('pedphase'),
                phaseid: ele.id, // 相位id，用于对应相位状态
                id: dir,
                name: this.PhaseDataModel.getSidePos(dir).name
              })
            }
          })
        }
      })
      return this.sidewalkPhaseData
    },
    getPed (data) {
      // if (data.length === 0) return
      let ped = []
      let peddirections = []
      let color = getTheme() === 'light' ? '#1E1E1E' : '#F1F3F4'
      for (let walk of this.sidewalkPhaseData) {
        // for (let ped of data) {
        let objs = {}
        objs.name = walk.name
        objs.id = walk.id
        objs.color = color
        if (data === walk.id) {
          peddirections.push(objs)
          peddirections = Array.from(new Set(peddirections))
        }
        // }
      }
      ped.push(...peddirections)
      return ped
    },
    initData () {
      let color = getTheme() === 'light' ? '#1E1E1E' : '#F1F3F4'
      let phasetype = getControSource(this.$i18n.locale)
      let patterntype = getOverLap(this.$i18n.locale)
      this.typeOptions = getTypeOptions()
      if (this.$i18n.locale === 'en') {
        this.typeOptions = getEtypeOptions()
      }
      this.typeOptions[0].children = phasetype
      this.typeOptions[1].children = phasetype
      this.typeOptions[2].children = patterntype
      this.typeOptions[3].children = patterntype
      let channel = this.globalParamModel.getParamsByType('channelList')
      let overlap = this.globalParamModel.getParamsByType('overlaplList')
      const phaseList = this.globalParamModel.getParamsByType('phaseList')
      const channelMap = {}
      for (let obj of channel) {
        channelMap[obj.id] = obj
      }
      // this.realdirOptions = new Map()
      for (let id in channelMap) {
        let obj = channelMap[id]
        let list = []
        list.push(obj.controltype)
        // 车道灯和不启用，没有下一级菜单
        if (obj.controltype !== 6 && obj.controltype !== 0) {
          list.push(obj.controlsource)
        }
        if (obj.controltype === 4 || obj.controltype === 5) {
          this.getPedPhasePos(overlap)
        } else {
          this.getPedPhasePos(phaseList)
        }
        if (obj.type === 0 || obj.type === 1 || obj.type === 3) {
          this.turnOptions.set(obj.id, this.carList)
          channelMap[obj.id].realtype = 'direction' // 使用映射
          if (obj.controltype === 4 || obj.controltype === 5) {
            if (!overlap.filter(phase => phase.id === obj.controlsource)[0].direction) {
              this.realdirOptions.set(obj.id, [])
              return
            }
            this.realdirOptions.set(obj.id, (overlap.filter(phase => phase.id === obj.controlsource)[0].direction ? overlap.filter(phase => phase.id === obj.controlsource)[0].direction : overlap.filter(phase => phase.id === obj.controlsource)[0].peddirection).map(item => ({value: item, item: [{ id: 0, peddirection: this.getPed(item), color: color }], label: overlap.filter(phase => phase.id === obj.controlsource)[0].direction ? getPhaseDesc([item], this.$i18n.locale) : getPedPhaseDesc([item], this.$i18n.locale)})))
          } else if (obj.controltype === 6) {
            let status = [
              {
                item: [{
                  id: 1,
                  color: color
                }],
                label: getPhaseDesc([1], this.$i18n.locale),
                value: 1
              },
              {
                item: [{
                  id: 2,
                  color: color
                }],
                label: getPhaseDesc([2], this.$i18n.locale),
                value: 2
              },
              {
                item: [{
                  id: 3,
                  color: color
                }],
                label: getPhaseDesc([3], this.$i18n.locale),
                value: 3
              },
              {
                item: [{
                  id: 4,
                  color: color
                }],
                label: getPhaseDesc([4], this.$i18n.locale),
                value: 4
              },
              {
                item: [{
                  id: 5,
                  color: color
                }],
                label: getPhaseDesc([5], this.$i18n.locale),
                value: 5
              },
              {
                item: [{
                  id: 6,
                  color: color
                }],
                label: getPhaseDesc([6], this.$i18n.locale),
                value: 6
              },
              {
                item: [{
                  id: 7,
                  color: color
                }],
                label: getPhaseDesc([7], this.$i18n.locale),
                value: 7
              },
              {
                item: [{
                  id: 8,
                  color: color
                }],
                label: getPhaseDesc([8], this.$i18n.locale),
                value: 8
              },
              {
                item: [{
                  id: 9,
                  color: color
                }],
                label: getPhaseDesc([9], this.$i18n.locale),
                value: 9
              },
              {
                item: [{
                  id: 10,
                  color: color
                }],
                label: getPhaseDesc([10], this.$i18n.locale),
                value: 10
              },
              {
                item: [{
                  id: 11,
                  color: color
                }],
                label: getPhaseDesc([11], this.$i18n.locale),
                value: 11
              },
              {
                item: [{
                  id: 12,
                  color: color
                }],
                label: getPhaseDesc([12], this.$i18n.locale),
                value: 12
              },
              {
                item: [{
                  id: 13,
                  color: color
                }],
                label: getPhaseDesc([13], this.$i18n.locale),
                value: 13
              },
              {
                item: [{
                  id: 14,
                  color: color
                }],
                label: getPhaseDesc([14], this.$i18n.locale),
                value: 14
              },
              {
                item: [{
                  id: 15,
                  color: color
                }],
                label: getPhaseDesc([15], this.$i18n.locale),
                value: 15
              },
              {
                item: [{
                  id: 16,
                  color: color
                }],
                label: getPhaseDesc([16], this.$i18n.locale),
                value: 16
              }
            ]
            channelMap[obj.id].realtype = 'direction' // 使用映射
            this.realdirOptions.set(obj.id, status)
          } else {
            this.realdirOptions.set(obj.id, this.globalParamModel.getParamsByType('phaseList').filter(phase => phase.id === obj.controlsource)[0].direction.map(item => ({value: item, item: [{ id: item, peddirection: [], color: color }], label: getPhaseDesc([item], this.$i18n.locale)})))
          }
        } else if (obj.type === 2) {
          channelMap[obj.id].realtype = 'peddirection' // 使用映射
          this.turnOptions.set(obj.id, this.peopleList)
          if (obj.controltype === 4 || obj.controltype === 5) {
            if (!overlap.filter(phase => phase.id === obj.controlsource)[0].peddirection) {
              this.realdirOptions.set(obj.id, [])
              return
            }
            this.realdirOptions.set(obj.id, (overlap.filter(phase => phase.id === obj.controlsource)[0].direction ? overlap.filter(phase => phase.id === obj.controlsource)[0].direction : overlap.filter(phase => phase.id === obj.controlsource)[0].peddirection).map(item => ({value: item, item: [{ id: 0, peddirection: this.getPed(item), color: color }], label: overlap.filter(phase => phase.id === obj.controlsource)[0].direction ? getPhaseDesc([item], this.$i18n.locale) : getPedPhaseDesc([item], this.$i18n.locale)})))
          } else {
            this.realdirOptions.set(obj.id, this.globalParamModel.getParamsByType('phaseList').filter(phase => phase.id === obj.controlsource)[0].peddirection.map(item => ({value: item, item: [{ id: 0, peddirection: this.getPed(item), color: color }], label: getPedPhaseDesc([item], this.$i18n.locale)})))
            // this.realdirOptions[obj.id - 1] = this.globalParamModel.getParamsByType('phaseList').filter(phase => phase.id === obj.controlsource)[0].direction.map(item => ({value: item, label: getPhaseDesc([item])}))
          }
          // this.realdirOptions[obj.id - 1] = this.globalParamModel.getParamsByType('phaseList').filter(phase => phase.id === obj.controlsource)[0].peddirection.map(item => ({value: item, label: getPedPhaseDesc([item])}))
        }
        obj.typeAndSouce = list
      }
    },
    handleChange (value, index, val) {
      let color = getTheme() === 'light' ? '#1E1E1E' : '#F1F3F4'
      let channel = this.globalParamModel.getParamsByType('channelList')
      // let phaseList = this.globalParamModel.getParamsByType('phaseList')
      let overlap = this.globalParamModel.getParamsByType('overlaplList')
      channel[index].controltype = value[0]
      if (value[1]) {
        channel[index].controlsource = value[1]
      }
      this.createCurrentDescMap()
      // 机动车相位2与跟随相位4
      if (value[0] === 2) {
        channel[index].type = 0
        channel[index].realdir = []
        this.turnOptions.set(val.id, this.carList)
        this.realdirOptions.set(val.id, this.globalParamModel.getParamsByType('phaseList').filter(phase => phase.id === value[1])[0].direction.map(item => ({value: item, item: [{ id: item, peddirection: [], color: color }], label: getPhaseDesc([item], this.$i18n.locale)})))
      //   // 行人相位3与行人跟随相位5
      } else if (value[0] === 3) {
        channel[index].type = 2
        channel[index].realdir = []
        this.turnOptions.set(val.id, this.peopleList)
        this.realdirOptions.set(val.id, this.globalParamModel.getParamsByType('phaseList').filter(phase => phase.id === channel[index].controlsource)[0].peddirection.map(item => ({value: item, item: [{ id: 0, peddirection: this.getPed(item), color: color }], label: getPedPhaseDesc([item], this.$i18n.locale)})))
      } else if (value[0] === 4) {
        channel[index].type = 0
        channel[index].realdir = []
        this.turnOptions.set(val.id, this.carList)
        if (!overlap.filter(phase => phase.id === channel[index].controlsource)[0].direction && !overlap.filter(phase => phase.id === channel[index].controlsource)[0].peddirection) {
          this.realdirOptions.set(val.id, [])
          return
        }
        this.realdirOptions.set(val.id, overlap.filter(phase => phase.id === channel[index].controlsource)[0].direction ? overlap.filter(phase => phase.id === channel[index].controlsource)[0].direction.map(item => ({value: item, item: [{ id: item, peddirection: [], color: color }], label: getPhaseDesc([item], this.$i18n.locale)})) : [])
      } else if (value[0] === 5) {
        channel[index].type = 2
        channel[index].realdir = []
        this.turnOptions.set(val.id, this.peopleList)
        if (!overlap.filter(phase => phase.id === channel[index].controlsource)[0].direction && !overlap.filter(phase => phase.id === channel[index].controlsource)[0].peddirection) {
          this.realdirOptions.set(val.id, [])
          return
        }
        this.realdirOptions.set(val.id, overlap.filter(phase => phase.id === channel[index].controlsource)[0].peddirection ? overlap.filter(phase => phase.id === channel[index].controlsource)[0].peddirection.map(item => ({value: item, item: [{ id: 0, peddirection: this.getPed(item), color: color }], label: getPedPhaseDesc([item], this.$i18n.locale)})) : [])
      } else {
        channel[index].type = 4
        channel[index].realdir = []
        this.turnOptions.set(val.id, [])
        this.realdirOptions.set(val.id, [])
      }
      // this.isChange = !this.isChange
    },
    createCurrentDescMap () {
      // 生成当前的控制类型描述，与通道id一一对应
      let channels = this.globalParamModel.getParamsByType('channelList')
      let desclist = new Map()
      for (let ele of channels) {
        if (!ele.typeAndSouce || ele.typeAndSouce.length === 0) continue
        let source
        let dire
        let desc = []
        if (ele.typeAndSouce[0] !== undefined) {
          source = this.typeOptions.filter(type => type.value === ele.typeAndSouce[0])[0].label
          desc[0] = source
        }
        if (ele.typeAndSouce[1] !== undefined) {
          this.typeOptions.forEach(type => {
            if (type.value === ele.typeAndSouce[0] && type.children && type.children.length) {
              dire = type.children.filter(child => child.value === ele.typeAndSouce[1])[0].label
            }
          })
          desc[1] = dire
        }
        desclist.set(ele.id, desc)
      }
      this.desclist = desclist
      // this.desclists = Array.from(desclist).map(item => {
      //   return {id: item[0], value: item[1][1].split('-')[1]}
      // })
      this.$store.dispatch('SetChannelDesc', desclist)
    },
    increaseId () { // 实现id在之前的基础上寻找最小的
      let channelList = this.globalParamModel.getParamsByType('channelList')
      let channelIdList = channelList.map(ele => ele.id)
      let i = channelList.length - 1
      if (i >= 0) {
        for (let j = 1; j <= 40; j++) {
          if (!channelIdList.includes(j)) {
            this.id = j
            return
          }
        }
      }
    },
    handleEdit (index, row) {

    },
    handleDelete (index, row) {
      this.$confirm(this.$t('edge.channel.deletetip'),
        this.$t('edge.common.alarm'), {
          confirmButtonText: this.$t('edge.common.confirm'),
          cancelButtonText: this.$t('edge.common.cancel'),
          type: 'warning'
        }).then(() => {
        this.globalParamModel.deleteParamsByType('channelList', index, 1)
        // 删除对应的通道描述，以供通道锁定和手动面板更新
        delete this.desclist[row.id]
        this.$store.dispatch('SetChannelDesc', this.desclist)
        this.$message({
          type: 'success',
          message: this.$t('edge.common.deletesucess')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('edge.common.deletecancel')
        })
      })
    },
    deleteAllData () {
      this.$confirm(this.$t('edge.channel.deleteAlltip'),
        this.$t('edge.common.alarm'), {
          confirmButtonText: this.$t('edge.common.confirm'),
          cancelButtonText: this.$t('edge.common.cancel'),
          type: 'warning'
        }).then(() => {
        let channelList = this.globalParamModel.getParamsByType('channelList')
        this.globalParamModel.deleteParamsByType('channelList', 0, channelList.length)
        this.id = 1
        this.$message({
          type: 'success',
          message: this.$t('edge.common.deletesucess')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('edge.common.deletecancel')
        })
      })
    },
    handleClone (index, row) {
      let data = {}
      this.increaseId()
      if (this.globalParamModel.getParamLength('phaseList') === 0) {
        this.$message.error(
          // 'Please create phase first !'
          this.$t('edge.pattern.firstphase')
        )
        return
      }
      if (this.globalParamModel.getParamLength('channelList') >= 40) {
        this.$message.error(
          // 'There are at most 255 data !'
          this.$t('edge.channel.mostdata')
        )
        return
      }
      Object.assign(data, row)
      data.id = this.id
      this.globalParamModel.addParamsByType('channelList', data)
      // this.id++
      // 重新排序相位数组
      let channelList = this.globalParamModel.getParamsByType('channelList')
      channelList.sort(this.compareProperty('id'))
    },
    onAdd () {
      if (this.globalParamModel.getParamLength('phaseList') === 0) {
        this.$message.error(
          // 'Please create phase first !'
          this.$t('edge.pattern.firstphase')
        )
        return
      }
      if (this.globalParamModel.getParamLength('channelList') >= 40) {
        this.$message.error(
          // 'There are at most 255 data !'
          this.$t('edge.channel.mostdata')
        )
        return
      }
      // this.getControSource()
      this.increaseId()
      var channelInitData = {
        id: this.id,
        desc: '',
        // turn: '',
        // type: '',
        controlsource: 1,
        // direction: 0,
        controltype: 2,
        typeAndSouce: [2, 1],
        voltthresh: 50,
        pacthresh: 30,
        peakhthresh: 400,
        peaklthresh: 130
      }
      this.globalParamModel.addParamsByType('channelList', channelInitData)
      // this.id++
      // 重新排序相位数组
      let channelList = this.globalParamModel.getParamsByType('channelList')
      channelList.sort(this.compareProperty('id'))
    },
    compareProperty (property) {
      return function (a, b) {
        var value1 = a[property]
        var value2 = b[property]
        return value1 - value2
      }
    },
    openWiringDiagram () {
      this.diagramVisible = true
    },
    closeWiringDiagram () {
      this.diagramVisible = false
    }
  }
}
</script>

<style scoped>
 /* * {
    margin: 0;
    padding: 0} */
  body {
      overflow: auto;
      font-weight: 400;
      -webkit-font-smoothing: antialiased;
    }
.tb-edit .el-input {
    display: none;
}
.tb-edit .current-row .el-input {
    display: block;
}
.tb-edit .current-row .el-input + span {
    display: none;
}
.tb-edit .el-select {
    display: none;
}
.tb-edit .el-cascader {
    display: none;
}
.tb-edit .current-row .el-select {
    display: block;
}
.tb-edit .current-row .el-select + span {
    display: none;
}
.tb-edit .current-row .el-cascader {
    display: block;
}
.tb-edit .current-row .el-cascader + span {
    display: none;
}
.tb-edit .el-input-number {
    display: none;
}
.tb-edit .current-row .el-input-number {
    display: block;
}
.tb-edit .current-row .el-input-number + span {
    display: none;
}
.tb-edit .el-col {
    display: none;
}
.tb-edit .current-row .el-col {
    display: block;
}
.tb-edit .current-row .el-col + span {
    display: none;
}
.tb-edit .el-popover {
    display: none;
}
.tb-edit .current-row .el-popover {
    display: block;
}
.tb-edit .current-row .el-popover + span {
    display: none;
}
.showSpan {
  display: block;
}
.tb-edit .current-row .showSpan {
  display: none;
}
  /* .el-cascader {
    display: inline-block;
    position: relative;
    font-size: 14px;
    line-height: 40px;
    width: 100%;
  } */
  .config {
    width: 100%;
  }
</style>
<style lang="scss">
  .WiringDiagram {
    .el-dialog__body {
      padding: 30PX;
    }
  }
</style>
